<?php
class Application_Model_StoreItem extends Application_Model_DomainObject{
	
	protected $_id;//序号

	protected $_productName;//商品名称
	
	protected $_orderItemId;//
	
	protected $_orderId;//订单号
        
        protected $_orderNo;//订单号
	
	protected $_price;//商品价格
	
	protected $_storeId;//仓库ID
	
	protected $_dateInStore;//入库时间
	
	protected $_dateOut;//出库时间
	
	protected $_quantity;//数量
	
	protected $_productId;//产品ID
        
        protected $_intype;//类型

        protected  $_state;//状态 0:未入库 1:已入库 2:已出库

        protected  $_logisticsname;//物流公司

        protected  $_logistics;//物流号

        protected  $_userid;

        protected  $_image;//图片

        protected  $_weight;//重量

        protected  $_product;//产品信息

        protected  $_remark;//备注

        protected  $_createdate;//记录创建时间

        protected  $_wayId;//运单序号

        protected  $_isPack;//是否有包装

        //12月4号新增
        protected $_bignessType; //体积重量类型

        protected $_isBrand; //是否仿牌

        protected $_isSpecific; //是否特殊的

        protected $_length;//长

        protected $_width;//宽

        protected $_height;//高

        protected $_volumeWeight;//体积重量

        protected $_canVacuum;//能否真空处理

        protected $_vacuumWeight;//真空处理后体积重量

        protected $_noPackageWeight;//去包将后重量

        protected $_isEmbargo;//是否禁运品

        protected $_itemType;//产品类型

        protected $_barcode;//条形码

        protected $_isSelected;//是否被选中

        protected $_cnShipFee;//国家运费

        protected $_wyid;//运单id

        protected $_isdelete;//删除判断

        protected $_embargoReason;

        protected $_locationNo;

        protected $_operateName;
        /**
         * 正常 
         */
        const TYPE_Normal=0;

        /**
         * 仿牌
         */
        const TYPE_Brand = 1;
        /**
         * 电池
         */
        const TYPE_Battery=2;//
        /**
         * 液体
         */
        const TYPE_Liquid=4;//
        /**
         * 食品
         */
        const TYPE_Food=8;//
        /**
         * 粉末
         */
        const TYPE_Powder=16;//

        /**
         * 膏状物 
         */
        const TYPE_Paste=32;

        /**
         *药物 
         */
        const TYPE_Drug=64;

        /**
         * 敏感物品 
         */
        const TYPE_Sensitive=128;

        /**
         * 已录单
         */
        const STATUS_CheckIn = 0;
        /**
         * 已入库 
         */
        const STATUS_InStored = 1;
        /**
         * 已拣货 
         */
        const STATUS_Picking = 3;    
        /**
         * 已出库 
         */
        const STATUS_Sended = 2;
        /**
         * 退货中
         */
        const STATUS_ReturnOf = 4;
        /**
         * 已经退货
         */
        const STATUS_AchieveRe = 5;
    
    public static function getStatusNames()
    {
        return array(Application_Model_StoreItem::STATUS_CheckIn => "已录单"
                ,  Application_Model_StoreItem::STATUS_InStored  => "已入库"
                ,  Application_Model_StoreItem::STATUS_Picking   => "已拣货"
                ,  Application_Model_StoreItem::STATUS_Sended    => "已出库"
                ,  Application_Model_StoreItem::STATUS_ReturnOf  => "退货中"
                ,  Application_Model_StoreItem::STATUS_AchieveRe =>'完成退货'
                );
    }
    public function getStatusName()
    {
        $arrStatusNames = self::getStatusNames();
        return $arrStatusNames[$this->_state];
    }
    
    public static function getNames(){
        return array('0'=>array('正常','','')
            ,'1'=>array('仿牌','tz5','仿牌是指仿冒名牌或没有正规发票的名牌产品。UPS和Fedex不接收仿牌，DHL牌子货通道，EMS、邮政小包可正常出货。')
            ,'2'=>array('电池','tz4','指物品中包含电池,DHL牌子货通道，EMS，邮政小包可正常出货。')
            ,'4'=>array('液体','tz3','敏感物品，只有EMS,邮政小包可接收少量液体，且必须与别的物品混合配送。')
            ,'8'=>array('食品','tz3','美国不能发送食品，其他可正常发货。')
            ,'16'=>array('粉末','tz4','敏感物品，只有EMS,邮政小包可接收少量粉末，且必须与别的物品混合配送。')
            ,'32'=>array('膏状','tz3','敏感物品，只有EMS,邮政小包可接收少量膏状物，且必须与别的物品混合配送。')
            ,'64'=>array('药物','tz3','敏感物品，只有EMS,邮政小包可接收少量药物。')
            ,'128'=>array('敏感','tz4','敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            ,'256'=>array('纯电池','tz4','指物品中包含电池,DHL牌子货通道，EMS，邮政小包可正常出货。')
            ,'512'=>array('保健品','tz4','敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            ,'1024'=>array('眼镜','tz4','敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            ,'2048'=>array('光盘','tz4','敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            );
    }


    public function getItemTypeName(){
        $names = Application_Model_StoreItem::getNames();
        if($this->_itemType==0){
            return $names['0'][0];
        }
        $nameAll='';
        if($this->_itemType){
            foreach($names as $key=>$name){
                if($key != 0 && ($this->ItemType & $key) == $key){
                   $nameAll = $nameAll. $name[0].';';                
                }
            }
        }
        return $nameAll;
    }

        
    /**
	 * 返回数据持久化对象
	 * @return Application_Model_StoreItem
	 */
	protected static function getDb(){
		return new Application_Model_DbTable_StoreItem(); 
	}
        
    public function getimageFile(){
        
        if($this->_image==null || $this->_image=='')
        {
            return Application_Model_Product::DEFAULT_IMAGE;
        }
        else
        {
            return $this->_image;
        }        
    }
        
    /*
        * 新增仓库单
        */
    public function  addItem(Application_Model_StoreItem $newItem){
        $newItem->save();
    }
        

        /**
	 * 根据userid返回一个仓库货物数组
	 * @param int $userid
	 * @return array
	 */
	public static function getByuserId($userid,$state,$start,$row){
            

        //$result=Application_Model_StoreItem::getDb()->queryAll(array('userid'=>$userid));//方案一            
        $result=Application_Model_StoreItem::getDb()->getByUser($userid,$state, $start,$row);//方案二

        foreach ($result as $item){
            if($item->productId!=null)
            {
                $item->product = new Application_Model_Product($item->productId);
            }
        }

        return $result;

	}

    /**
        *根据id列表获取仓库信息
        * @param type $ids id列表,如：1,2,3
        * @return type  仓库数组
        */
    public static function  getByids($ids){
        $result=Application_Model_StoreItem::getDb()->getByids($ids);

        

        return $result;
    }


    /*
        * 根据用户名，状态获取当前仓库记录总数
        * @param int $userid 用户序号
        * @param int $state 用户序号
    * @return int
        */
    public  static function getItemCount($userid,$state){

        $store=new Application_Model_DbTable_StoreItem(); 

        return $store->getItemCount($userid, $state);
    }

    public  static function getInTypeCount($userid,$state){

        $store=new Application_Model_DbTable_StoreItem(); 

        return $store->getInTypeCount($userid, $state);
    }

    public static function  getBywayId($wayid){
        $store=new Application_Model_DbTable_StoreItem(); 

        return $store->getBywayId($wayid);
    }
        
    /**
     * 根据指定的条件返回
     * @param int $wayid
     * @param int $memberId
     * @param date $startTime 开始时间
     * @param date $endTime 结束时间
     * @param int $status 订单状态
     * @param int $count
     * @param int $offset
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($wayid,$memberId,$startTime,$endTime, $status, $count, $offset){
        $where = array();
        $and = '';
        if($wayid != NULL){
            $where['Id = '] = $wayid;
            $and = ' and ';
        }
        
        if ($memberId != NULL){
            $where[$and.' userId = '] = $memberId;
            $and = ' and ';
        }
        
        if($startTime != NULL){
            $where[$and.' dateInStore >= '] = $startTime;
            $and = ' and ';
        }
        
        if($endTime != NULL){
            $where[$and.' dateInStore <= '] = $endTime;
            $and = ' and ';
        }
        
        if ($status != NULL){
            $where[$and.' state = '] = $status;
            $and = ' and ';
        }
        
        return Application_Model_StoreItem::getDb()->queryPage($where, 'id desc ', $count, $offset);        
    }
    
    public static function getMyStore($memberId,$count,$offset){
        return Application_Model_StoreItem::getByFilter(NULL, $memberId, NULL, NULL, 1, $count, $offset);
    }
    
    /**
     * 是否是禁止选择的选项
     * @return type 
     */
    public function isDisabled(){
        return $this->_state != Application_Model_StoreItem::STATUS_InStored || $this->_isEmbargo;
    }
    
    /**
     * 是否已经选中
     * @return type 
     */
    public function isSelect(){
        return $this->_isSelected && !$this->isDisabled();
    }
    
    /**
     * 返回所有已经选中仓库项
     * @param type $userid
     * @return type 
     */
    public static function getMySelect($userid){
        return Application_Model_StoreItem::getDb()->queryAll(array('userid'=>$userid,'isSelected'=>1,'state'=>  Application_Model_StoreItem::STATUS_InStored));
    }
    
    /**
     * 返回体积重量
     * @param type $array
     * @return type 
     */
    public static function getSumVolumeWeight($array){
        $weight = 0;
        foreach ($array as $item){
            if($item->VolumeWeight){
                $weight += $item->VolumeWeight;
            }  else {
                $weight += $item->Weight;
            }
        }
        return $weight;
    }

    /**
     * 返加总重量
     * @param type $array 
     */
    public static function getSumWeight($array){
        $weight =0;
        foreach ($array as $key){
            $weight += $key->weight;
        }
        return $weight;
    }
    /**
     * 获取今日入库的包裹数量
     */
    public static function getcountinstore()
    {
        $where[' dateInStore >='] = date('Y-m-d');
        $where[' and state = '] = Application_Model_StoreItem::STATUS_InStored;
        return Application_Model_StoreItem::getDao()->count($where);
    }
    /**
     * 获取今日出库的包裹数量
     */
    public static function getcountoutstore()
    {
        $where[' dateInStore >='] = date('Y-m-d');
        $where[' and state = '] = Application_Model_StoreItem::STATUS_Sended;
        return Application_Model_StoreItem::getDao()->count($where);
    }
    public static function countstore($status)
    {
        if ($status != '') {
            if($status == 1){
                $where[' dateInStore >'] = date('Y-m-d');
            }else{
                $where[' dateOut >'] = date('Y-m-d');
            }
            //$where['and  state = '] =  $status;
            return Application_Model_StoreItem::getDao()->count($where);
        }else{
            return 0;
        }
    }
    
    public static function countnotscan(){
        $where = array();
        $where['(state= '] = self::STATUS_CheckIn;
        $where[' or state= '] = self::STATUS_InStored;
        $where[') and (locationNo = "" or locationNo is null) and '] = 1;
        return self::getDao()->count($where);
    }
    
    public static function coustore($userid){
        $where[' userid = '] = $userid;
        $where[' and state = '] = Application_Model_StoreItem::STATUS_InStored;
        return Application_Model_StoreItem::getDao()->count($where);
    }
    /**
     * 根据userid，加载user对象
     * @author wuzw
     * @return type
     */
    public function getuserinfo() {
        if ($this->_userid) {
            return Application_Model_User::load($this->_userid);
        }
    }

    public static function getMyByFilter($quick, $dateinbegin, $dateinend, $state, $day, $isdel, $count, $offset, $notscan) {
        $where = array();
        $and = '';
//            $hasUserCon = false;

        $user_where = "";

        if ($quick != NULL) {
            $and = "(";
            $user_where[" nikename like "] = "%" . $quick . "%";
            $user_where[" or storeno = "] = $quick;
            $userItem = Application_Model_User::getDao()->queryAll($user_where);
            if ($userItem) {
                $userarrid = "";
                foreach ($userItem as $uservalue) {
                    $userarrid.= $uservalue->id . ",";
                }
                $where[$and . " userid in "] = "(" . $userarrid . "0)";
                $and = " or ";
            }
            $where[$and . ' orderno like '] = '%' . $quick . '%';
            $and = " or ";
            $where[$and . ' operateName like '] = '%' . $quick . '%';
            $where[$and . ' barcode like '] = '%' . $quick . '%';
            $where[" ) and "] = 1;
            $and = " and ";            
        }
        if ($day != 1) {
            if ($dateinbegin != NULL) {
                $where[$and . ' dateInStore >= '] = $dateinbegin;
                $and = ' and ';
            }

            if ($dateinend != NULL) {
                $where[$and . ' dateInStore <= '] = $dateinend;
                $and = ' and ';
            }
        } else {
            if ($state == 2) { //出库
                $where[$and . ' dateOut >= '] = date('Y-m-d');
                $and = ' and ';
            } else { //入库
                $where[$and . ' createdate >= '] = date('Y-m-d');
                $and = ' and ';
            }
        }
        if ($state != NULL) {
            $where[$and . ' state = '] = $state;
            $and = ' and ';
        }
        if ($isdel != NULL) {
            $where[$and . " isdelete = "] = $isdel;
            $and = " and ";
        } else {
            $where[$and . " (isdelete is null or  isdelete = '' ) and "] = 1;
            $and = " and ";
        }
        if($notscan == "notscan"){
            $where[$and.'(state= '] = self::STATUS_CheckIn;
            $where[' or state= '] = self::STATUS_InStored;
            $where[') and (locationNo = "" or locationNo is null) and '] = 1; 
        }
//            var_dump($where);exit;
        return Application_Model_StoreItem::getDb()->queryPage($where, "  id desc ", $count, $offset);
    }

    public static function bybarcode($barcode) {
        $where[" barcode like "] = "%" . $barcode . "%";
        return Application_Model_StoreItem::getDao()->queryOne($where);
    }

    public static function surebybarcode($barcode) {
        $where[" barcode = "] = $barcode;
        return Application_Model_StoreItem::getDao()->queryOne($where);
    }
    /*
     * 根据用户id获取用户仓库号
     */

    public function getbystoreno() {
        $userid = $this->_userid;
        return Application_Model_User::load($userid);
    }

    public function delstore($idlist) {
        $arrid = explode(",", $idlist);
        foreach ($arrid as $key => $value) {
            if ($value != '') {
                $where['id = '] = $value;
                $result = Application_Model_StoreItem::getDao()->queryOne($where);
                $result->state = Application_Model_StoreItem::STATUS_Sended;
                $result->isdelete = 1;
                $result->save();
                Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_delstore, $result->Logistics, $result->userid);
            }
        }
        return true;
    }

    public static function getstoreuser($idlist) {
        $arrid = explode(",", $idlist);
        foreach ($arrid as $key => $value) {
            if ($value != '') {
                $uwhere['id = '] = $value;
                $result = Application_Model_StoreItem::getDao()->queryOne($uwhere);
                if ($result->state == Application_Model_StoreItem::STATUS_Sended && ( $result->wayId != null || $result->wayId != "" || $result->wayId != 0)) {
                    return 2;
                }
            }
        }
        $id = "(" . $idlist . "0)";
        $where[" id in "] = $id;
        $storeItem = Application_Model_StoreItem::getDao()->queryAll($where);
        foreach ($storeItem as $value) {
            $arruser[$value->userid] = 1;
        }
        if (count($arruser) == 1) {
            return $storeItem;
        } else {
            return 4;
        }
    }

    public static function byselsstore($id, $userid, $count, $offset) {
        $where[" id in "] = "(" . $id . "0)";
        $where[" and userid = "] = $userid;
        $where[" and state = "] = Application_Model_StoreItem::STATUS_InStored;
        $where[" and (wayId = "] = "";
        $where[" or wayId is null ) and "] = 1;
        return Application_Model_StoreItem::getDao()->queryPage($where, " id desc ", $count, $offset);
    }

    public static function bysurplusstore($id, $userid, $count, $offset) {
        $where[" id not in "] = "(" . $id . "0)";
        $where[" and userid = "] = $userid;
        $where[" and state = "] = Application_Model_StoreItem::STATUS_InStored;
        $where[" and (wayId = "] = "";
        $where[" or wayId is null ) and "] = 1;
        return Application_Model_StoreItem::getDao()->queryPage($where, " id desc ", $count, $offset);
    }
    public static function Bywyid($wyid){
            if($wyid){
                $where[' wyid = '] = $wyid;
                return Application_Model_StoreItem::getDao()->queryAll($where);
            }
            return null;
    }
    public function addImg($imgurl)
    {
        $imgItem = new Application_Model_StoreImg();
        $imgItem->storeid = $this->_id;
        $imgItem->imgurl = $imgurl;
        $imgItem->save();
    }
    
    public function getStoreIdWay()
    {
        return Application_Model_WayItem::getDao()->queryAll(array("storeItemId"=>  $this->_id));
    }
    
    public static function openNewLocation($userid){
        $weight = 0;
        $res = self::getDao()->queryAll(array('userid'=>$userid));
        foreach($res as $val){
            if($val->volumeWeight){
                $weight += $val->volumeWeight;
            }else{
                $weight += $val->weight;
            }            
        }
        $quantity = 0;
        foreach($res as $val){
            $quantity += $val->quantity;
   
        }
        $count = Application_Model_StoreLocation::getDao()->count(array('userId'=>$userid));
        if($count<=1){
            $count = 1;
        }
        $vweight = $weight/1000/$count;
        if($vweight > 20 || $quantity > (15*$count)){
            return 1;
        }else{
            return 0;
        }
    }
    
    
}